package pl.peterjack.servlet.uslugi;

import java.io.IOException;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pl.peterjack.model.PMF;
import pl.peterjack.model.dane.Faktura;
import pl.peterjack.model.dane.Firma;
import pl.peterjack.model.pdf.MyXML;
import pl.peterjack.model.pdf.PdfGenerator;
import pl.peterjack.model.pdf.impl.PdfGeneratorFaktura;

import com.itextpdf.text.DocumentException;

public class PdfFaktura extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(PdfFaktura.class.getName());
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	    throws IOException {
			if(request.getParameter("id")==null || "".equals(request.getParameter("id"))) {
				return; 
			}
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Long id = Long.parseLong((String)request.getParameter("id")); 
		    Faktura faktura = pm.getObjectById(Faktura.class, id);
		    Firma firma = (Firma) request.getSession().getAttribute("firma");
		    if (firma == null) {
				request.getSession().invalidate();
				response.setContentType("text/plain");
				response.setStatus(response.SC_MOVED_TEMPORARILY);
				response.setHeader("Location", "/");
				return; 
			}
			response.setContentType("application/pdf");
			org.jdom.Element stylXML;
			try {
				
				stylXML = MyXML.getRootByStylXML(firma.getStylXml()); 
				PdfGenerator pdfGenerator = new PdfGeneratorFaktura(faktura, stylXML);
				pdfGenerator.generujPdf(response.getOutputStream());
			} catch (DocumentException e) {
				throw new IOException();
			} catch (Exception e1) {
				e1.printStackTrace();
				throw new IOException();	
			} finally {
				pm.close();
			}
			

	}

	

}
